//
//  HSWebViewController.m
//  mobile
//
//  Created by li on 2017/9/27.
//  Copyright © 2017年 li. All rights reserved.
//

#import "HSWebViewController.h"
//#import "ImagePickerTool.h"
#import "PlateIDCameraViewController.h"
#import "IDCardCameraViewController.h"
//#import <MTAHybrid.h>
//#import <WXApi.h>
//#import <LCActionSheet.h>
#import <BlocksKit+UIKit.h>
#import "CarNoInputView.h"
#import <JPUSHService.h>
#import "UIImage+Wechat.h"

@interface HSWebViewController ()<WKNavigationDelegate,WKNavigationDelegate,WKUIDelegate>

@property (nonatomic,strong) UIBarButtonItem *backItem;
@property (nonatomic, strong) UIProgressView *progressView;
//保存导航栏设置
@property (nonatomic, strong) NSDictionary *navigationParam;

@property (nonatomic, strong) CarNoInputView *inputView;

@end

@implementation HSWebViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = kMainColor;
    [self addSubView];
    [self jsbridge];
    kShowAnimationLoadingView(self.view)
    
    if([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    }
}

- (void)addSubView {
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenW, 0.1)];
    [self.view addSubview:view];
    
    WKWebViewConfiguration *conf = [[WKWebViewConfiguration alloc] init];
    conf.processPool = [[WKProcessPool alloc] init];
    conf.userContentController = [[WKUserContentController alloc] init];
    
    _webView = [[WKWebView alloc] initWithFrame:CGRectZero configuration:conf];
    _webView.navigationDelegate = self;
    _webView.UIDelegate = self;
    _webView.allowsBackForwardNavigationGestures = NO;
    _webView.backgroundColor = [UIColor whiteColor];
    _webView.scrollView.bouncesZoom = NO;
    _webView.scrollView.bounces = NO;
    [_webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
    [_webView addObserver:self forKeyPath:@"loading" options:NSKeyValueObservingOptionNew context:nil];
    [_webView addObserver:self forKeyPath:@"canGoBack" options:NSKeyValueObservingOptionNew context:nil];
    [_webView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:nil];
    
    if (_urlString) {
        NSURL *url = [[NSURL alloc] initWithString:_urlString];
    
        [_webView loadRequest:[NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:20]];
    }
    
    self.backItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"public_backArrow"] style:(UIBarButtonItemStylePlain) target:self action:@selector(back)];
    self.navigationItem.leftBarButtonItem = self.backItem;
    
    _progressView = [[UIProgressView alloc] init];
    _progressView.progressTintColor = [UIColor colorWithRed:206/255.0 green:7/255.0 blue:85/255.0 alpha:1.0];
    _progressView.progress = 0;
    _progressView.tintColor = [UIColor greenColor];
    
    [self.view addSubview:_webView];
    [self.view addSubview:_progressView];
    
    [_webView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(0);
        make.right.mas_equalTo(0);
        make.top.mas_equalTo(0);
        make.bottom.mas_equalTo(0);
    }];
    
    [_progressView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(0);
        make.right.mas_equalTo(0);
        make.top.mas_equalTo(self.webView.mas_top);
        make.height.mas_equalTo(2);
    }];

}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:YES];
    [self setNavigation];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:YES];
    
    [self.navigationController.navigationBar setBackgroundImage:[HSTool createImageWithColor:kMainColor andHeight:1] forBarMetrics:UIBarMetricsDefault];
    [HSTool setStatusBarBackgroundColor:kMainColor];
    if([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = YES;
    }
    
//    NSArray *viewControllers = self.navigationController.viewControllers;
//    if (viewControllers.count > 1 && [viewControllers objectAtIndex:viewControllers.count-2] == self) {//PUSH
//    
//    }else{//pop
//        HSLog(@"返回");
//        self.navigationController.navigationBarHidden = NO;
//    }
}

- (void)setUrlString:(NSString *)urlString{
    
    if (!(urlString.length)) {
        return;
    }
    HSLog(@"设置的URL: %@",urlString);
    
    if ([urlString containsString:@"#"]) {
        NSArray *arr = [urlString componentsSeparatedByString:@"#"];
        if (arr.count == 2) {
            NSString *str = [arr lastObject];
            str = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            urlString = [NSString stringWithFormat:@"%@#%@",[arr firstObject],str];
        }
    }else{
        urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    }
    
    _urlString = urlString;
    
    NSURL *url = [[NSURL alloc] initWithString:_urlString];
//     [_webView loadRequest:[NSURLRequest requestWithURL:url]];
    [_webView loadRequest:[NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:20]];
}

- (void)back{
    if (_webView.canGoBack) {
        [_webView goBack];
        return;
    }
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)close{
//    NSArray *arr = _webView.backForwardList.backList;
//    [_webView goToBackForwardListItem:[arr firstObject]];
    [UIAlertView bk_showAlertViewWithTitle:@"确认退出吗" message:nil cancelButtonTitle:@"算了" otherButtonTitles:@[@"退出"] handler:^(UIAlertView *alertView, NSInteger buttonIndex) {
        if (buttonIndex == 1) {
             [self.navigationController popViewControllerAnimated:YES];
        }
        
    }];
   
}

//弹窗
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler{
    
    kShowAlertMsg(message);
    completionHandler();
}

- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{
    
    NSURL *URL = navigationAction.request.URL;
    NSString *scheme = [URL scheme];
    
    // 打电话
    if ([scheme isEqualToString:@"tel"]) {
         UIApplication *app = [UIApplication sharedApplication];
        if ([app canOpenURL:URL]) {
            
            if (kSystemVersion <= 10.2) {
                [UIAlertView bk_showAlertViewWithTitle:URL.resourceSpecifier ?:@"" message:nil cancelButtonTitle:@"取消" otherButtonTitles:@[@"呼叫"] handler:^(UIAlertView *alertView, NSInteger buttonIndex) {
                    if (buttonIndex == 1) {
                        [app openURL:URL];
                    }
                }];
            }else{
                [app openURL:URL];
            }

            decisionHandler(WKNavigationActionPolicyCancel);
            return;
        }
    }else if ([scheme isEqualToString:@"sms"]){
        UIApplication *app = [UIApplication sharedApplication];
        if ([app canOpenURL:URL]) {
            [app openURL:URL];
            decisionHandler(WKNavigationActionPolicyCancel);
            return;
        }
    }
    
    //如果是跳转一个新页面
    if (navigationAction.targetFrame == nil) {
        [webView loadRequest:navigationAction.request];
    }
    
    decisionHandler(WKNavigationActionPolicyAllow);
}

#pragma mark 进度条
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    
    kWeakSelf

    if (object == self.webView && [keyPath isEqualToString:@"estimatedProgress"]) {
        CGFloat newprogress = [[change objectForKey:NSKeyValueChangeNewKey] doubleValue];
        if (newprogress == 1) {
            self.progressView.hidden = YES;
            [self.progressView setProgress:0 animated:NO];
        }else {
            self.progressView.hidden = NO;
            [self.progressView setProgress:newprogress animated:YES];
        }
    }else if (object == self.webView &&[keyPath isEqualToString:@"loading"]){
        kHideAnimationLoadingView(weakSelf.view);
    }else if (object == self.webView && [keyPath isEqualToString:@"canGoBack"]){
        dispatch_async(dispatch_get_main_queue(), ^{
        
            if (weakSelf.webView.canGoBack) {
                self.navigationItem.leftBarButtonItem = weakSelf.backItem;
            }else{
                self.navigationItem.leftBarButtonItems  = nil;
            }
        });
        
    }else if (object == self.webView && [keyPath isEqualToString:@"frame"]){
        dispatch_async(dispatch_get_main_queue(), ^{
           weakSelf.progressView.y = weakSelf.webView.y;
        });
        
    }else if (object == self.webView && [keyPath isEqualToString:@"title"]){
        dispatch_async(dispatch_get_main_queue(), ^{
            if (!kStringIsEmpty(self.webView.title)) {
                self.title = self.webView.title;
            }
        });
    }
}


#pragma mark JSBridge
- (void)jsbridge{
    _bridge = [WKWebViewJavascriptBridge bridgeForWebView:_webView];
    [_bridge setWebViewDelegate:self];

    [self jsLoginSuccess];
    [self jsGetDeviceInfo];
    [self jsSetNavigation];
    [self jsSetNavigationItem];
    [self jsCloseWeb];
//    [self jsGetLocation];
    [self jsClearWebCache];
    [self jsLog];
    [self jsGetCarNo];
    [self jsOpenCarNoInputView];
    [self getCardInfo];
    
}

- (void)jsLoginSuccess{
    kWeakSelf
    [_bridge registerHandler:kJSLoginSuccess handler:^(id data, WVJBResponseCallback responseCallback) {
        NSString *userId = data[@"id"];
        HSLog(@"当前用户ID： %@",userId);
        [weakSelf jpushAddAlias:userId];
    }];
}

- (void)jpushAddAlias:(NSString *)userId{
    [JPUSHService deleteAlias:^(NSInteger iResCode, NSString *iAlias, NSInteger seq) {
        [JPUSHService setAlias:userId completion:^(NSInteger iResCode, NSString *iAlias, NSInteger seq) {
        } seq:1];
    } seq:2];
}


- (void)jsGetDeviceInfo{
    [_bridge registerHandler:kJSGetDeviceInfo handler:^(id data, WVJBResponseCallback responseCallback) {
        
        NSString *systemVersion = [UIDevice currentDevice].systemVersion;
        NSString *result = [NSString stringWithFormat:@"{systemName:\"%@\",OSVersion:\"%@\"}",@"iPhone",systemVersion];
        
        responseCallback(result);
    }];
}

- (void)jsSetNavigation{
    
    kWeakSelf
    [_bridge registerHandler:kJSSetNavigation handler:^(id data, WVJBResponseCallback responseCallback) {
        weakSelf.navigationParam = data;
        [weakSelf setNavigation];
    }];
}

- (void)setNavigation{
    if (kDictIsEmpty(self.navigationParam)) {
        return;
    }
    NSDictionary *dic = self.navigationParam;
    kWeakSelf
    if (dic[@"title"]) {
        weakSelf.title = dic[@"title"];
    }
    
    if (dic[@"color"]) {
        UIColor *color = [HSTool colorWithHexString:dic[@"color"] alpha:1];
        [weakSelf.navigationController.navigationBar setBackgroundImage:[HSTool createImageWithColor:color andHeight:1] forBarMetrics:UIBarMetricsDefault];
    }
    
    if (weakSelf.navigationController.navigationBarHidden != [dic[@"hidden"] boolValue]) {
        
        dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC));
        
        dispatch_after(delayTime, dispatch_get_main_queue(), ^{
            [weakSelf.navigationController setNavigationBarHidden:[dic[@"hidden"] boolValue] animated:NO];
        });
    }
    
    if(dic[@"statusColor"]){
        UIColor *color = [HSTool colorWithHexString:dic[@"statusColor"] alpha:1];
        [HSTool setStatusBarBackgroundColor:color];
    }
}

//type:(0文字 1图片)
//content:(文字内容或，图片url)

//JS设置右侧导航栏按钮
- (void)jsSetNavigationItem{
    kWeakSelf
    [_bridge registerHandler:kJSSetNavigationItem handler:^(id data, WVJBResponseCallback responseCallback) {      
        NSString *json = data[@"content"];
        NSArray *arr = [HSTool getDictionaryFromString:json];
        
        NSMutableArray *items = [NSMutableArray array];
        
        for (int i = (int)arr.count-1;i >= 0;i--) {
            NSDictionary *dic = arr[i];
            int type = [dic[@"type"] intValue];
            NSString *result = [NSString stringWithFormat:@"{index:%d}",i];
            
            if (type == 0) {
                NSString *title = dic[@"text"] ?:@"";
                UIBarButtonItem *item = [[UIBarButtonItem alloc] bk_initWithTitle:title style:(UIBarButtonItemStylePlain) handler:^(id sender) {
                    responseCallback(result);
                }];
                [items addObject:item];
            }else{
                NSString *url = dic[@"url"] ?:@"";
                NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:url]];
                UIImage *image = [UIImage imageWithData:data];
                UIBarButtonItem *item = [[UIBarButtonItem alloc] bk_initWithImage:image style:(UIBarButtonItemStylePlain) handler:^(id sender) {
                    responseCallback(result);
                }];
                [items addObject:item];
            }
        }
        
        weakSelf.navigationItem.rightBarButtonItems = items;
        
    }];
}

- (void)jsCloseWeb{
    kWeakSelf
    [_bridge registerHandler:kJSCloseWeb handler:^(id data, WVJBResponseCallback responseCallback) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf.navigationController popViewControllerAnimated:YES];
        });
    }];
}




//- (void)jsGetLocation{
//    
//    [_bridge registerHandler:kJSGetLocation handler:^(id data, WVJBResponseCallback responseCallback) {
//
//        LocationTool *tool = [LocationTool sharedInstance];
//        [tool start];
//        tool.getLocationBlock = ^(BOOL isSuccess, NSString *errorMessage, LocationModel *model) {
//
//            if (!isSuccess) {
//                NSString *msg = [NSString stringWithFormat:@"定位失败:%@",errorMessage?:@""];
//                kShowAlertMsg(msg);
//                return ;
//            }
//
//            NSString *result = [NSString stringWithFormat:@"{longitude:\"%@\",latitude:\"%@\",province:\"%@\",city:\"%@\",district:\"%@\",streetName:\"%@\",businessCircle:\"%@\"}",model.longitude,model.latitude,model.addressDetail.province,model.addressDetail.city,model.addressDetail.district,model.addressDetail.streetName,model.businessCircle?:@""];
//            HSLog(@"JS回调结果:%@",result);
//            responseCallback(result);
//        };
//    }];
//}

- (void)jsClearWebCache{
    kWeakSelf
    [_bridge registerHandler:kJSClearWebCache handler:^(id data, WVJBResponseCallback responseCallback) {
        [HSTool clearWebCache];
        kAutoHideLoadingView(weakSelf.view, @"清除成功", 1);
    }];
}

- (void)jsLog{
    [_bridge registerHandler:kJSLog handler:^(id data, WVJBResponseCallback responseCallback) {
        NSDictionary *dic = data;
        HSLog(@"JS打印的日志:%@",dic[@"content"]);
    }];
}



- (void)jsGetCarNo{
    
    [_bridge registerHandler:kJSGetCarNo handler:^(id data, WVJBResponseCallback responseCallback) {

        PlateIDCameraViewController *vc = [[PlateIDCameraViewController alloc] init];

        vc.carIdContent = ^(NSString *result){
            if (result.length == 7 || result.length == 8) {
                NSString *resultString = [NSString stringWithFormat:@"{carNo:\"%@\"}",result];
                responseCallback(resultString);
            }
            HSLog(@"车牌是:%@",result);
        };
        [self presentViewController:vc animated:YES completion:nil];
    }];
}

//车牌输入和识别
- (void)jsOpenCarNoInputView{
    kWeakSelf
    [_bridge registerHandler:kCarNoInputView handler:^(id data, WVJBResponseCallback responseCallback) {
        dispatch_async(dispatch_get_main_queue(), ^{
            //            kScreenW/2.0 + 10 + 40
            weakSelf.inputView = [[CarNoInputView alloc] initWithFrame:CGRectMake(0,weakSelf.view.height - ( kScreenW/2.0 + 50) - 50, kScreenW, 50)];
            weakSelf.inputView.backgroundColor = [UIColor whiteColor];
            weakSelf.inputView.vc = weakSelf;
            weakSelf.inputView.carNoInputBlock = ^(NSString *carNo) {
                if (carNo.length == 7 || carNo.length == 8) {
                    NSString *resultString = [NSString stringWithFormat:@"{carNo:\"%@\"}",carNo];
                    responseCallback(resultString);
                }
                [self.inputView removeFromSuperview];
            };
            weakSelf.inputView.removeSelfBlock = ^{
                [self.inputView removeFromSuperview];
            };
            [weakSelf.inputView showKeyBoardView];
            [self.view addSubview:weakSelf.inputView];
        });
        
    }];
}


//证件识别
- (void)getCardInfo{
    [_bridge registerHandler:kJSGetCardInfo handler:^(id data, WVJBResponseCallback responseCallback) {
        NSDictionary *dic = data;
        int type = [dic[@"type"] intValue];
        
        IDCardCameraViewController *cameraVC = [[IDCardCameraViewController alloc] init];
        cameraVC.mainID = type;
        cameraVC.typeName = @{
                              @2 : @"居民身份证",
                              @5 : @"机动车驾驶证",
                              @6 : @"机动车行驶证",
                              @28 : @"机动车驾驶证副页"
                              }[@(type)];
        
        cameraVC.subID = 0;
        cameraVC.cropType = 0;
        cameraVC.recogOrientation = RecogInVerticalScreen;
        cameraVC.carIdContent = ^(NSDictionary *resultDic, UIImage *image) {
            image = [image wcSessionCompress];
            NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:resultDic];
//            NSString *base64 = [HSTool getBase64Image:image];
//            HSLog(@"%@",base64);
            
//            dic[@"image"] = base64;
            NSMutableString *resultString = [NSMutableString stringWithString:@"{"];
            
            for (NSString *key in dic.allKeys) {
                [resultString appendFormat:@"%@:\"%@\",",key,dic[key]];
            }
            if (resultDic.allValues.count) {
                [resultString replaceCharactersInRange:NSMakeRange(resultString.length-1, 1) withString:@"}"];
            }
            
            //            NSString *result = [HSTool getStringFromDictionary:resultDic];
            //HSLog(@"证件识别结果:%@",resultString);
            responseCallback(resultString);
        };
        [self presentViewController:cameraVC animated:YES completion:nil];
        
    }];
}

- (void)printQuote{
    [_bridge registerHandler:kJSPrintQuote handler:^(id data, WVJBResponseCallback responseCallback) {
        NSDictionary *dic = data;
        HSLog(@"---%@",dic);
    }];
}

- (void)dealloc{
     [self removeAllObserver];
//     [HSTool clearWebCache];
}
- (void)removeAllObserver{
    @try {
        [self.webView removeObserver:self forKeyPath:@"estimatedProgress"];
        [self.webView removeObserver:self forKeyPath:@"loading"];
        [self.webView removeObserver:self forKeyPath:@"canGoBack"];
        [self.webView removeObserver:self forKeyPath:@"title"];
    } @catch (NSException *exception) {

    } @finally {
    }
}

@end
